﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

/// <summary>
///GetClientIP 的摘要说明
/// </summary>
public class GetClientIP
{
	public static string get()
	{
        return HttpContext.Current.Request.UserHostAddress;
	}
    public static string getIP()
    {
        string ip = "";
        if (HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null) // using proxy
        {

            ip = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();  // Return real client IP.

        }

        else// not using proxy or can't get the Client IP
        {

            ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString(); //While it can't get the Client IP, it will return proxy IP.

        }
        return ip;
    }
    public static string getIP3()
    {
        string userHostAddress = HttpContext.Current.Request.UserHostAddress;

        if (string.IsNullOrEmpty(userHostAddress))
        {
            userHostAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
        }

        //最后判断获取是否成功，并检查IP地址的格式（检查其格式非常重要）
        if (!string.IsNullOrEmpty(userHostAddress) && IsIP(userHostAddress))
        {
            return userHostAddress;
        }
        return "127.0.0.1";
    }
    /// <summary>
/// 检查IP地址格式
/// </summary>
/// <param name="ip"></param>
/// <returns></returns>
public static bool IsIP(string ip)
{
    return System.Text.RegularExpressions.Regex.IsMatch(ip, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$");
}
}